package com.bjsxt;
/**线程同步
 * 银行取钱案例*/

//用户类
class Account01 {
    private String accountNo;//账户
    private double balance;//账户的余额
    public Account01(){}

    public Account01(String accountNo, double balance) {
        this.accountNo = accountNo;
        this.balance = balance;
    }

    public String getAccountNo() {
        return accountNo;
    }

    public void setAccountNo(String accountNo) {
        this.accountNo = accountNo;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }
}
//取钱线程
class DrawMoney extends Thread {
    //账户对象
    private Account01 account01;
    //取钱金额
    private double drawMoney;
    //创建构造方法，方便参数传递
    public DrawMoney(String name,Account01 account01,double drawMoney){
        super(name);
        this.account01=account01;
        this.drawMoney=drawMoney;
    }
    //取钱线程
    @Override
    public void run() {
        synchronized (this.account01){
            if(this.account01.getBalance()>=this.drawMoney){
                System.out.println(this.getName()+"取钱成功"+this.drawMoney);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                this.account01.setBalance(this.account01.getBalance()-this.drawMoney);
                System.out.println("\t"+"余额："+this.account01.getBalance());

            }else {
                System.out.println(this.getName()+"取钱先败");
            }
        }
    }
}
public class DrawMoneyThread02 {
    public static void main(String[] args) {
        //先实例化账户
        Account01 account01 = new Account01("221",1000);
        //实例化线程
        DrawMoney drawMoney = new DrawMoney("老公",account01,800);
        DrawMoney drawMoney1 = new DrawMoney("老婆",account01,800);
        drawMoney.start();
        drawMoney1.start();
    }

}
